package cn.juc;

import lombok.extern.slf4j.Slf4j;

/**
 * 二阶段终止模式
 * 新版可以使用 volatile
 */
@Slf4j
public class TwoStepEnd {
    private Thread MonitorThread;
    public void start(){
       MonitorThread=new Thread(()->{
           while (true){
               if (Thread.currentThread().isInterrupted()){
                   log.info("打断了");
                   break;
               }
               log.info("执行监听");
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
                   Thread.currentThread().interrupt();
               }
           }
       });
       MonitorThread.start();
    }
    public void end(){
        MonitorThread.interrupt();//打断
    }

    public static void main(String[] args) throws InterruptedException {
        TwoStepEnd twoStepEnd=new TwoStepEnd();
        twoStepEnd.start();
        Thread.sleep(5000);
        twoStepEnd.end();
    }
}
